package com.appspot.niehonglei.action;

import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.niehonglei.common.Tools;
import com.appspot.niehonglei.dao.PMF;
import com.appspot.niehonglei.jdo.Index;
import com.google.appengine.api.datastore.Text;

public class SaveIndex implements ActionInterface {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {

		String category = request.getParameter("category");
		String comeFrom = request.getParameter("comeFrom");
		String author = request.getParameter("author");
		String content = request.getParameter("content");
		String title = request.getParameter("title");
		String id = request.getParameter("id");
		try {
			if (content != null && !"".equals(content)) {
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Index index = null;
				if(id!=null && !"".equals(id)){
					index = pm.getObjectById(Index.class,Long.valueOf(id));
					index.setContent(new Text(content));
					index.setChangeDate(Tools.shiftDate(new Date()));
				} else {
					index = new Index(new Text(content));
				}
				if (category != null && !"".equals(category)) {
					index.setCategory(category);
				}
				if (comeFrom != null && !"".equals(comeFrom)) {
					index.setComeFrom(comeFrom);
				}
				if (author != null && !"".equals(author)) {
					index.setAuthor(author);
				}
				if (title != null && !"".equals(title)) {
					index.setTitle(title);
				}

				pm.makePersistent(index);
				pm.close();
			}
			response.sendRedirect("/publish?new");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
